#!/bin/bash

# Make sure we're running from the root git repository, not whatever submodule
# we could have been called from.
pushd $(dirname "$0") > /dev/null

VERSION="UNKNOWN"
BUILDNUMBER=dev

# Call git describe, and convert it to a semi-semantic version, like
# 5.0.0-alpha.0+dev.52.g123abc
generate_dev_version() {
    git describe | perl -pe "s/(.*)-([0-9]*)-(g[0-9a-f]*)/\1${1}dev.\2.\3/"
}

generate_version() {

    METADATA_SEPARATOR=${1:-+}

    # If we are in a Git repository and have git installed, build the version
    # string using the latest tag in case it's reachable
    if type git >/dev/null 2>&1 && [ -d '.git' ] ; then

        # Check for tag reachability, in case of shallow clones we might not
        # be able to use git describe since the commit which was tagged is
        # unreachable even if we have pulled the tags. If we can reach it,
        # overwrite the VERSION from autoconf with the output, else append
        # HEAD commit info
        if git describe >/dev/null 2>&1 ; then
            VERSION=$(generate_dev_version ${METADATA_SEPARATOR})
        else
            VERSION+=.g
            VERSION+=$(git rev-parse --short HEAD)
        fi
    fi
}

FLAG="${1:-noflag}"
if [ "$FLAG" = '--image' ] ; then
    generate_version "."
else
    generate_version "+"
fi

echo "${VERSION}"
popd > /dev/null
